<template>
	<div class="main">
		<div class="main-form">
			<van-form @submit="onSubmit">
				<van-cell-group inset>
					<van-field
						v-model="tel"
						name="tel"
						label="手机号"
						placeholder="手机号"
						:rules="[{ required: true, message: '请填写手机号' }]"
					></van-field>
					<van-field
						v-model="sms"
						name="sms"
						center
						clearable
						label="短信验证码"
						placeholder="短信验证码"
						:rules="[
							{ required: true, message: '请输入短信验证码' },
						]"
					>
						<template #button>
							<van-button
								size="small"
								type="primary"
								@click="sendCode"
								>发送验证码</van-button
							>
						</template>
					</van-field>
					<van-field
						v-model="password"
						name="password"
						label="密码"
						placeholder="密码"
						:rules="[{ required: true, message: '请填写密码' }]"
					></van-field>
				</van-cell-group>

				<van-button type="primary" block class="zhuce" @click="register"
					>快速注册</van-button
				>
			</van-form>
		</div>
	</div>
</template>
<script setup>
import { ref, onMounted } from "vue"
import { useRouter } from "vue-router"
import { Field, CellGroup, Form, Button, showNotify } from "vant"

import {
	sendCheckCode,
	checkCheckCode,
	completeRegister,
} from "../services/index"

const tel = ref("")
const password = ref("")
const sms = ref("")
const onSubmit = (values) => {
	console.log("submit", values)
}

const router = useRouter()

// 获取验证码
const sendCode = async () => {
	const telVal = tel.value.trim()
	const telPhone =
		/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/
	if (telPhone.test(telVal)) {
		const sendCode = await sendCheckCode(tel.value)
		console.log(sendCode)
	} else {
		showNotify({ type: "primary", message: "请输入正确格式的手机号" })
	}
}

// 验证验证码是否正确
const register = async () => {
	const register = await checkCheckCode(tel.value, sms.value)
	const result = completeRegister(tel.value, password.value)
	if (password.value === "") {
		showNotify({ type: "primary", message: "请输入密码" })
		// router.push("/login")
	} else if (
		register.data.code === "200" &&
		(await result).data.code === "200"
	) {
		console.log(register)
		showNotify({ type: "primary", message: "注册成功" })
	} else {
		showNotify({ type: "primary", message: "验证码输入有误" })
	}
}
</script>
<style scoped>
.main-form {
	margin-top: 20px;
}
.zhuce {
	margin: 20px auto;
	width: 350px;
}
</style>
